layui.use(['layer', 'form','laydate'], function () {
    var $ = layui.jquery;
    var laydate = layui.laydate;

    var currentBridge = {//当前桥梁
        beamNo:null,
        bridgeName:null
    }

    var realTimeData;//实时挠度数据
    var periodTime = 3600000;//1小时的毫秒数

    var stand_bend_render_base64 = null;//标准挠度趋势图的64位url
    var ssndInterval = null;//更新实施数据定时器
    var ssndLineChart = null;//实时挠度echarts图实例
    var ssndLineOption = null;//实时挠度echarts配置

    var mapChart = null;//地图echarts实例
    var mapOption = null;//地图配置
    var curDate = $(".curDate");

    var loading = null;



    // // 渲染时间选择框
    laydate.render({
        elem: '#date_range',
        trigger: 'click',
        range: true
    });

    var height = $(window).height();
    $(".main").height(height - 70);


    init('');

    //右上角时间
    setInterval(function() {
        curDate.text(function() {
            var d = new Date();
            var vYear = d.getFullYear();
            var vMon = d.getMonth() + 1;
            var vDay = d.getDate();
            var h = d.getHours();
            var m = d.getMinutes();
            var se = d.getSeconds();
            var nowTime = vYear+ "-"+(vMon<10 ? "0" + vMon : vMon)+ "-"+(vDay<10 ? "0"+ vDay : vDay)+ "    "+(h<10 ? "0"+ h : h)+ ":"+(m<10 ? "0" + m : m)+ ":"+(se<10 ? "0" +se : se);
            return nowTime;
        });
    },1000);




    //切换右上角实时图和趋势图
    $(".infoDiv .info-item").click(function(){
        $(this).addClass("move");
        $(this).prevAll().removeClass("move");
        $(this).nextAll().removeClass("move");
    });

    //下载报告
    $("#file-download").click(function(){

        var form = document.getElementById('postData_form');
        document.getElementById("_beamNo").value=currentBridge.beamNo;
        document.getElementById("_img64Url").value=stand_bend_render_base64;

        var startDate = null;
        var endDate = null;
        var time_limit = $("#date_range").val();
        if(time_limit != null && time_limit != ''){
            var timeArr = time_limit.split(" - ");
            startDate = timeArr[0];
            endDate = timeArr[1];
        }
        document.getElementById("_startDate").value=startDate;
        document.getElementById("_endDate").value=endDate;


        form.submit();
        form = null;
    });

    //时间限制搜索
    $("#search-btn1").click(function (){
        var beamNo = $("#beamNo");
        if(beamNo == null ){
            return;
        }
        //突发荷载预警(重型荷载的恢复时间查询)
        var time_limit = $("#date_range");
        if(time_limit == null){
            return;
        }
        var timeArr = time_limit.val().split(" - ");;
        if(timeArr == null || timeArr.length !=2){
            return;
        }
        var startDate = timeArr[0].replace(/-/g,"");
        var endDate = timeArr[1].replace(/-/g,"");
        scatterPayloadRecover(beamNo.val(),startDate,endDate);
        //荷载分布
        piePayloadCount(beamNo.val(),startDate,endDate);
        //挠度极限预警
        pieNdjx(beamNo.val(),startDate,endDate);
    });

    //桥梁搜索
    $("#search-btn2").click(function (){
        var search_val = $("#search").val();
        init(search_val);

    });


    //左上角地图加载
    function initMapData(bridgeData){
        var scattleData = createMapScattle(bridgeData);
        if(mapChart == null){
            mapChart = echarts.init(document.getElementById("map-charts"));
            mapOption = {
                title: {
                    left:"center",
                    top:'30',
                    text: '桥梁分布',
                    textStyle: {
                        fontWeight:'normal',
                        color: '#fff',
                        fontSize:18
                    }
                },
                color:['#02DBC6'],
                tooltip: {
                    trigger: 'item',
                    formatter: function(params){
                        if(params.data && params.data.value){
                            return params.name;
                        }
                    }
                },
                geo: {
                    name: '桥梁分布',
                    roam: true,
                    map: 'china',
                    label: {
                        normal: {
                            show: false
                        },
                        emphasis: {
                            show: false
                        }
                    },
                    itemStyle: {
                        normal: {
                            areaColor: '#0F3060',
                            borderColor:'#009CFF',
                            borderWidth:1
                        },
                        emphasis: {
                            areaColor: '#0F3060'
                        }
                    },
                },
                series:[
                    {
                        name: '桥梁点图',
                        type: 'scatter',
                        coordinateSystem: 'geo',
                        data : scattleData,
                        symbolSize: function (value,param) {
                            var beamNo=param.data.beamNo;
                            if(beamNo ==currentBridge.beamNo){
                                return 20;
                            }
                            return 12;
                        },
                        label: {
                            normal: {
                                show: false
                            },
                            emphasis: {
                                show: false
                            }
                        },
                        itemStyle: {
                            normal:{
                                color:'rgb(0,238,201)'
                            },
                            emphasis: {
                                borderColor: '#fff',
                                borderWidth: 1
                            }
                        }
                    }
                ]
            };
            mapChart.setOption(mapOption,true);

            //点击地图桥梁点
            mapChart.on('click', function (params) {
                if(params.seriesType == 'scatter'){

                    currentBridge.beamNo = params.data.beamNo;
                    currentBridge.bridgeName = params.data.bridgeName;
                    console.log("select bridge:"+params.data.bridgeName+" beam_no:"+params.data.beamNo+" current beamNo"+currentBridge.beamNo)
                    showDesc(params.data);


                    initMapData(bridgeData);
                    initEcharts();
                }
            });
        }else{
            mapOption.series[0].data = scattleData;
            mapChart.setOption(mapOption,true);
        }

    }

    function createMapScattle(bridgeData){
        var data = [];
        var len = bridgeData.length;
        while(len--) {
            var bridge = bridgeData[len];
            data.push({
                name : bridge.bridgeName,
                value: [bridge.lng,bridge.lat],
                managerOrg:bridge.managerOrg,
                maintainOrg:bridge.maintainOrg,
                line:bridge.line,
                stakeCode:bridge.stakeCode,
                bridgeName:bridge.bridgeName,
                beamNo:bridge.beamNo

            })
        }
        return data;
    }

    function showDesc(data){
        var desc = '';
        if(data.managerOrg){
            desc+= "<p>"+data.managerOrg+"</p>";
        }
        if(data.maintainOrg){
            desc+= "<p>"+data.maintainOrg+"</p>";
        }
        if(data.line){
            desc+= "<p>"+data.line+"</p>";
        }
        if(data.stakeCode){
            desc+= "<p>"+data.stakeCode+"</p>";
        }
        if(data.bridgeName){
            desc+= "<p>"+data.bridgeName+"</p>";
        }
        if(data.beamNo){
            desc+= "<p>"+data.beamNo+"</p>";
        }
        //桥梁文字描述
        $(".map-bridge-desc").html(desc);
        //
        var beamNo = data.beamNo;
        if(beamNo){

        }
    }

//疲劳趋势图
    function linePlqs(beamNo){

        stand_bend_render_base64 = null;

        $.get("/dataView/staticStandBendByYear?beamNo="+beamNo,function(data){
            if(data.success==true){
                data = data.data;
                var color= ["#2BBB3A","#833EBE","#1F72CB","#B4A73D","#47CAB0"]
                var series = new Array();
                var keys = data['keys'];
                var legendData = new Array();
                if(keys && keys.length>0){
                    $.each(data['data'],function(k,v){
                        legendData.push(v['year']);
                        var json = {
                            name:v['year'],
                            type:'line',
                            symbol: 'circle',
                            symbolSize:8,
                            itemStyle: {
                                normal: {
                                    color: color[k],
                                    lineStyle: {
                                        width:2,
                                        type: 'solid',
                                        color:color[k]
                                    }
                                }
                            },
                            data:v['data']
                        };
                        series.push(json);
                    })
                }
                var lineChart = echarts.init(document.getElementById("line-charts2"));
                var option={
                    title : {
                        x:'center',
                        text:  '疲劳趋势图',
                        textStyle: {
                            fontWeight:'normal',
                            color: '#fff',
                            fontSize:18
                        }
                    },

                    legend: {
                        data: legendData,
                        top: '40',
                        center:'center',
                        textStyle: {
                            fontSize:14,
                            color: '#fff'
                        },
                        paddingTop: '30'
                    },
                    grid: {
                        top:'80',
                        left: '80',
                        right: '20',
                        bottom: '45'
                    },
                    tooltip : {
                        trigger: 'axis',
                        textStyle:{
                            fontSize:14
                        },
                    },
                    xAxis : [
                        {
                            type : 'category',
                            boundaryGap : true,
                            nameGap: 30,
                            axisTick: {
                                show: false,
                                interval :0
                            },
                            axisLine: {
                                show: true,
                                lineStyle:{
                                    color:'#014876',
                                    width:2
                                }
                            },
                            axisLabel:{
                                interval :0,
                                margin:'10',
                                textStyle: {
                                    color: '#69c7ff',
                                    fontSize:14
                                }
                            },
                            data :keys
                        }
                    ],
                    yAxis : [
                        {
                            splitLine: {show: false},
                            axisTick: {
                                show: false,
                                interval :0
                            },
                            axisLine: {
                                show: true,
                                lineStyle:{
                                    color:'#014876',
                                    width:2
                                }
                            },
                            axisLabel:{
                                interval :0,
                                margin:'10',
                                textStyle: {
                                    color: '#69c7ff',
                                    fontSize:14
                                }
                            },
                            type : 'value'
                        }
                    ],
                    series:series
                };
                lineChart.setOption(option,true);
                stand_bend_render_base64 = lineChart.getDataURL();
            }

        });


    }
//实时挠度
    function drawLineSsnd(){

        var bendData = realTimeData['bendValue'];
        if(bendData == null){
            return;
        }

        if(ssndLineChart == null){
            ssndLineChart = echarts.init(document.getElementById("line-charts1"));//实时挠度线图

        }
        if(ssndLineOption == null || ssndLineOption =={}){
            ssndLineOption={
                title : {
                    left:'center',
                    top: '25',
                    text: "",
                    textStyle: {
                        fontWeight:'normal',
                        color: '#fff',
                        fontSize:18
                    }
                },
                legend: {
                    data: "实时挠度监控",
                    top: '55',
                    right:'20',
                    textStyle: {
                        fontSize:14,
                        color: '#fff'
                    },
                    paddingTop: '30'
                },
                grid: {
                    top:'80',
                    left: '80',
                    right: '20',
                    bottom: '45'
                },
                tooltip : {
                    trigger: 'axis',
                    textStyle:{
                        fontSize:14
                    },
                    // formatter: '{a0}: {c0}</br>'+'{a1}: {c1}'
                    formatter:function (params) {
                        var str = timeStamp2String(params[0]['data'][0])+"</br>";
                        for(var i=0;i<params.length;i++){
                            var param = params[i];
                            var marker = '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:'+param.color+'"></span>'
                            str+=marker+param.seriesName+':'+param['data'][1]+'</br>'
                        }
                        return str;
                    }
                },
                // dataZoom: [{
                //     type: 'inside'
                // }, {
                //     type: 'slider',
                //     showDetail:false
                // }],
                xAxis : [
                    {
                        type : 'time',
                        axisTick: {
                            show: false,
                            //interval :0
                        },
                        splitLine: {
                            show: false
                        },
                        axisLine: {
                            show: true,
                            lineStyle:{
                                color:'#014876',
                                width:2
                            }
                        },
                        axisLabel:{
                            interval :0,
                            margin:'10',
                            textStyle: {
                                color: '#69c7ff',
                                fontSize:14
                            }
                        },
                        //data :time
                    }
                ],
                yAxis : [
                    //y轴1，用于挠度
                    {
                        splitLine: {show: false},
                        axisTick: {
                            show: false,
                            interval :0
                        },
                        axisLine: {
                            show: true,
                            lineStyle:{
                                color:'#014876',
                                width:2
                            }
                        },
                        axisLabel:{
                            interval :0,
                            margin:'10',
                            textStyle: {
                                color: '#69c7ff',
                                fontSize:14
                            }
                        },
                        type : 'value',
                        name:'挠度(mm)',
                        nameTextStyle:{
                            color: '#69c7ff',
                            fontSize:14
                        }
                    },
                    // y轴2用于温度
                    {
                        splitLine: {show: false},
                        axisTick: {
                            show: false,
                            interval :0
                        },
                        axisLine: {
                            show: true,
                            lineStyle:{
                                color:'#014876',
                                width:2
                            }
                        },
                        axisLabel:{
                            interval :0,
                            // margin:'10',
                            textStyle: {
                                color: '#69c7ff',
                                fontSize:14
                            }
                        },
                        type : 'value',
                        name:'温度(°C)',
                        nameTextStyle:{
                            color: '#69c7ff',
                            fontSize:14
                        }
                    }
                ],
                series : [
                    {
                        name:'实时挠度',
                        type:'line',
                        showSymbol: false,
                        hoverAnimation: false,
                        itemStyle: {
                            normal: {
                                color: '#2BBB3A',
                                lineStyle: {
                                    width:1,
                                    type: 'solid',
                                    color:'#2BBB3A'
                                },
                                areaStyle: {
                                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1,[
                                            {offset: 1, color: 'rgba(43,187,58,0)'},
                                            {offset: 0, color: 'rgba(43,187,58,.4)'}
                                        ]
                                    )
                                }
                            }
                        },
                        yAxisIndex: 0,
                        data:[]
                    },

                    {
                        name:'静态位移',
                        type:'line',
                        showSymbol: false,
                        hoverAnimation: false,
                        //              smooth:true,
                        itemStyle: {
                            normal: {
                                color: '#1F72CB',
                                lineStyle: {
                                    width:1,
                                    type: 'solid',
                                    color:'#1F72CB'
                                },
                                areaStyle: {
                                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1,[
                                            {offset: 1, color: 'rgba(31,114,203,0)'},
                                            {offset: 0, color: 'rgba(31,114,203,.4)'}
                                        ]
                                    )
                                }
                            }
                        },
                        yAxisIndex: 0,
                        data:realTimeData['staticDisplayment']
                    },
                    {
                        name:'实时温度',
                        type:'line',
                        showSymbol: false,
                        hoverAnimation: false,
                        itemStyle: {
                            normal: {
                                color: '#833EBE',
                                lineStyle: {
                                    width:1,
                                    type: 'solid',
                                    color:'#833EBE'
                                },
                                areaStyle: {
                                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1,[
                                            {offset: 1, color: 'rgba(131,62,190,0)'},
                                            {offset: 0, color: 'rgba(131,62,190,.4)'}
                                        ]
                                    )
                                }
                            }
                        },
                        yAxisIndex: 1,
                        data:realTimeData['temperature']
                    }

                ]
            };
        }
        ssndLineOption.title.text = currentBridge.bridgeName;
        ssndLineOption.series[0]["data"] = realTimeData['bendValue'];

        ssndLineOption.series[1]["data"] = realTimeData['staticDisplayment'];
        ssndLineOption.series[2]["data"] = realTimeData['temperature'];
        ssndLineChart.clear();

        ssndLineChart.setOption(ssndLineOption,true);
        if(loading != null){
            closeLoading();
        }


    }

    /**
     * 实时挠度增量数据处理
     * @param addedDate 新增的数据
     * @param time 原始数据最新截止时间
     */
    function ssndDataHandler(addedDate){

        if(addedDate['bendValue'] !=null){
            var len = addedDate['bendValue'].length;
            var spliceTime = addedDate['bendValue'][len-1][0]-periodTime;//分隔时间戳，要把原始数据小于该时间戳的删除掉，并加上新的数据
            realTimeData.bendValue = addRealTimeData(realTimeData.bendValue,spliceTime,addedDate.bendValue);
            realTimeData.staticDisplayment = addRealTimeData(realTimeData.staticDisplayment,spliceTime,addedDate.staticDisplayment);
            realTimeData.temperature = addRealTimeData(realTimeData.temperature,spliceTime,addedDate.temperature);
        }
    }

    /**
     *
     * @param data 原始数据
     * @param time 删除小于该时间戳的数据
     * @param addDate 新增数据
     * @returns {any[]}
     */
    function  addRealTimeData(data,time,addDate) {

        var arr = new Array();
        if(data!=null){
            for(var i=0;i<data.length;i++){
                if(data[i][0]>time){
                    arr.push(data[i]);
                }
            }
            data = null;
        }

        return arr.concat(addDate);

    }


    /**
     * 荷载分布
     */
    function piePayloadCount(beamNo,startDate,endDate){
        //重/轻荷载分布
        $.get("/dataView/payloadCount?beamNo="+beamNo+"&startDate="+startDate+"&endDate="+endDate,function(data){
            if(data.success==true){
                data = data.data;
                var pieChart = echarts.init(document.getElementById("bar-charts3"));
                var option = {
                    title:{
                        text: '荷载分布',
                        x:'center',
                        textStyle: {
                            fontWeight:'normal',
                            color: '#fff',
                            fontSize:18
                        }
                    },
                    tooltip : {
                        trigger: 'item',
                        formatter: "{a} <br/>{b} : {c} ({d}%)"
                    },
                    legend: {
                        data:['轻型','重型'],
                        top: '30',
                        center:'center',
                        textStyle: {
                            fontSize:14,
                            color: '#fff'
                        },
                        paddingTop: '30'
                    },

                    series : [
                        {
                            name:'荷载分布',
                            type:'pie',
                            radius : [55, 90],
                            center: ['50%', '60%'],
                            // for funnel
                            // x: '60%',
                            width: '35%',
                            // funnelAlign: 'left',
                            // max: 1048,
                            labelLine: {
                                normal: {
                                    show: false
                                }
                            },

                            data:[
                                {
                                    value:data['1'],
                                    name:'轻型',
                                    itemStyle:{
                                        normal: {
                                            color:'#2BBB3A'
                                        }
                                    }
                                },
                                {
                                    value:data['2'],
                                    name:'重型',
                                    itemStyle:{
                                        normal: {
                                            color:'#3fb1e3'
                                        }
                                    }
                                }

                            ]
                        }
                    ]
                };
                pieChart.setOption(option,true);
            }
        });
    }

    //突发荷载预警开始
    function scatterPayloadRecover(beamNo,startDate,endDate){
        $.get("/dataView/payloadRecoverQuery?beamNo="+beamNo+"&startDate="+startDate+"&endDate="+endDate,function(data){
            if(data.success==true){
                data = data.data;
                var point_option = {
                    title : {
                        text: '突发预警荷载',
                        subtext: '',
                        x:'center',
                        textStyle: {
                            fontWeight:'normal',
                            color: '#fff',
                            fontSize:18
                        }
                    },
                    tooltip : {
                        // trigger: 'axis',
                        showDelay : 0,
                        formatter : function (params) {
                            return  timeStamp2String(params.value[0]) +'<br/>'
                                + params.value[1];

                        },
                        axisPointer:{
                            show: true,
                            type : 'cross',
                            lineStyle: {
                                type : 'dashed',
                                width : 1
                            }
                        }
                    },
                    legend: {
                        data: ['6秒内','6秒~60秒','60秒~12小时','大于12小时'],
                        top: '30',
                        center:'center',
                        textStyle: {
                            fontSize:14,
                            color: '#fff'
                        },
                        paddingTop: '30'
                    },

                    // backgroundColor:backgroundColor,
                    // color:color,
                    xAxis : [
                        {
                            type : 'time',
                            axisTick: {
                                show: false,
                                //interval :0
                            },
                            splitLine: {
                                show: false
                            },
                            axisLine: {
                                show: true,
                                lineStyle:{
                                    color:'#014876',
                                    width:2
                                }
                            },
                            axisLabel:{
                                interval :0,
                                margin:'10',
                                textStyle: {
                                    color: '#69c7ff',
                                    fontSize:14
                                }
                            },
                        },
                        // {
                        //     type : 'time',
                        //     scale:true,
                        //     axisLabel : {
                        //         formatter: '{value} ',
                        //         textStyle: {
                        //             color: '#B4A73D',
                        //             fontSize:14
                        //         }
                        //     },
                        //     splitLine: {
                        //         show: false
                        //     },
                        //     axisLine: {
                        //         show: true,
                        //         lineStyle: {
                        //             color: '#014876',
                        //             width: 2
                        //         }
                        //     }
                        // }
                    ],
                    yAxis : [
                        {
                            type : 'value',
                            scale:true,
                            axisLabel : {
                                formatter: '{value} ',
                                textStyle: {
                                    color: '#69c7ff',
                                    fontSize:14
                                }
                            },
                            axisLine: {
                                show: true,
                                lineStyle: {
                                    color: '#014876',
                                    width: 2
                                }
                            },
                            splitLine: {
                                show: false
                            }
                        }
                    ],
                    series : [
                        {
                            name:'6秒内',
                            type:'scatter',
                            data: data['6Second'],
                            itemStyle: {
                                normal: {
                                    color: '#2BBB3A'
                                }
                            }
                        },
                        {
                            name:'6秒~60秒',
                            type:'scatter',
                            data: data['6To1Min'],
                            itemStyle: {
                                normal: {
                                    color: '#1F72CB'
                                }
                            }
                        },
                        {
                            name:'60秒~12小时',
                            type:'scatter',
                            data: data['1MinTo12Hour'],
                            itemStyle: {
                                normal: {
                                    color: '#B4A73D'
                                }
                            }
                        },
                        {
                            name:'大于12小时',
                            type:'scatter',
                            data: data['morethan12Hour'],
                            itemStyle: {
                                normal: {
                                    color: '#833EBE'
                                }
                            }
                        }
                    ]
                };
                var pointChart = echarts.init(document.getElementById('point-charts'));
                pointChart.setOption(point_option,true);
            }
        });
    }

//挠度极限预警(重型荷载超过预设阈值的百分比)
    function pieNdjx(beamNo,startDate,endDate){
        //挠度极限预警
        $.get("/dataView/extremityCount?beamNo="+beamNo+"&startDate="+startDate+"&endDate="+endDate,function(data){
            if(data.success==true){
                data = data.data;
                var pie_option2 = {
                    title : {
                        text: '挠度极限预警',
                        x:'center',
                        textStyle: {
                            fontWeight:'normal',
                            color: '#fff',
                            fontSize:18
                        }
                    },
                    tooltip : {
                        trigger: 'item',
                        formatter: "{b} : {c} ({d}%)"
                    },
                    legend: {
                        data: ['储备','安全','预警','报警'],
                        top: '30',
                        center:'center',
                        textStyle: {
                            fontSize:14,
                            color: '#fff'
                        },
                        paddingTop: '30'
                    },
                    series : [
                        {
                            name: '',
                            type: 'pie',
                            // radius : '55%',
                            radius : [55, 90],
                            center: ['50%', '60%'],
                            avoidLabelOverlap: false,
                            labelLine: {
                                normal: {
                                    show: false
                                }
                            },
                            data:[
                                {
                                    value:data['1'],
                                    name:'储备',
                                    itemStyle: {
                                        normal: {
                                            color: '#47CAB0'
                                        }
                                    }
                                },
                                {
                                    value:data['2'],
                                    name:'安全',
                                    itemStyle: {
                                        normal: {
                                            color: '#2BBB3A'
                                        }
                                    }
                                },
                                {
                                    value:data['3'],
                                    name:'预警',
                                    itemStyle: {
                                        normal: {
                                            color: '#F0D33A'
                                        }
                                    }
                                },
                                {
                                    value:data['4'],
                                    name:'报警',
                                    itemStyle: {
                                        normal: {
                                            color: '#FA7C4C'
                                        }
                                    }
                                },
                            ],
                            // itemStyle: {
                            //     emphasis: {
                            //         shadowBlur: 10,
                            //         shadowOffsetX: 0,
                            //         shadowColor: 'rgba(0, 0, 0, 0.5)'
                            //     }
                            // }
                        }
                    ]
                };
                var pieChart2 = echarts.init(document.getElementById('pie-charts1'));
                pieChart2.setOption(pie_option2,true);
            }
        });

    }

    //创建echarts图 疲劳趋势图/实时挠度数据图/突发荷载预警/荷载分布/挠度极限图
    function initEcharts(){
        var beamNo = currentBridge.beamNo;

        openLoading();
        clearSSndInterval();
        echartsRemove();

        $("#beamNo").val(beamNo);
        realTimeData = {};
        //疲劳趋势(查询桥梁每天的标准静态挠度)
        linePlqs(beamNo);
        //实时挠度数据

        queryAndParseRealDate(new Date().getTime()-periodTime,true);
        //突发荷载预警(重型荷载的恢复时间查询)
        scatterPayloadRecover(beamNo,'','');
        //荷载分布
        piePayloadCount(beamNo,'','');
        //挠度极限预警
        pieNdjx(beamNo,'','');

    }


    function echartsRemove() {
        if(ssndLineChart != null){
            ssndLineChart.clear();
        }

        // $(".line-charts1").empty();
        //
        // $(".point-charts").empty();
        // $(".pie-charts1").empty();
        // $(".bar-charts3").empty();
        // $(".line-charts2").empty();
    }

    function init(searchBridgeVal){

        $.get("/dataView/monitorInfoSummary",function(data){
            //桥梁共**座 监测**座  占比*% 预警：*座  报警*座 修复*座
            if(data.success==true){
                data = data.data;
                var str = "桥梁共"+data.managerCount+"座 监测"+data.monitorCount+"座 占比"+data.rate+" 预警"+data.warnCount+"座 报警"+data.alarmCount+"座 修复"+data.maintainCount+"座";
                $(".monitor-summary").html(str)
            }

        });
        $.get("/bridge/list?condition="+searchBridgeVal,function(data){
            if(data.success==true){
                var bridges = data.data;
                if(bridges && bridges.length>0){
                    var bridge = bridges[0];
                    currentBridge.beamNo = bridge.beamNo;
                    currentBridge.bridgeName = bridge.bridgeName;
                    initMapData(bridges);
                    initEcharts();
                    showDesc(bridge);
                }
            }
        });
    }



    //清除实时数据的定时更新
    function clearSSndInterval() {
        if(ssndInterval != null){
            clearInterval(ssndInterval);
        }
    }
    //
    function createSsndInterval(){

        //实时挠度
        ssndInterval = setInterval(function() {
            if(currentBridge.beamNo != null ){
                var bendValueArr = realTimeData['bendValue'];
                var realTimeEnd = null//实时数据截止时间
                if(bendValueArr !=null){
                    realTimeEnd = bendValueArr[bendValueArr.length-1][0];
                }else{
                    realTimeEnd = (new Date().getTime())-periodTime;
                }
                queryAndParseRealDate(realTimeEnd,false);

            }
        },4000);
    }

    function timeStamp2String(time){
        var datetime = new Date();
        datetime.setTime(time);
        var year = datetime.getFullYear();
        var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
        var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
        var hour = datetime.getHours()< 10 ? "0" + datetime.getHours() : datetime.getHours();
        var minute = datetime.getMinutes()< 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
        var second = datetime.getSeconds()< 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
        var milliseconds = datetime.getMilliseconds();
        return year + "-" + month + "-" + date+" "+hour+":"+minute+":"+second+":"+milliseconds;
    }

    //连接influxdb获取实时数据
    function queryAndParseRealDate(startTime,setInterval){
        var sql = getTimeGranularitySql(startTime);
        console.log(sql);
        influxDbQuery.query(sql,function (data) {
            if(data !=null && data.results != null && data.results.length>0){
                var addDate = {};
                addDate.bendValue = new Array();//挠度
                addDate.temperature = new Array();//温度
                addDate.staticDisplayment = new Array();
                addDate.displayment = new Array();
                var series = data.results[0].series;
                if(series !=null && series.length>0){
                    var values = series[0].values;

                    //如果有时间间隔插入空数据
                    if(values != null && values.length>0){
                        for(var i=0;i<values.length;i++){
                            var v = values[i];

                            var time = v[0];
                            addDate.bendValue.push([time,v[3]==null?"":v[3].toFixed(2)]);
                            addDate.temperature.push([time,v[1]==null?"":v[1].toFixed(2)]);
                            addDate.staticDisplayment.push([time,v[2]==null?"":v[2].toFixed(2)]);
                        }
                    }
                    ssndDataHandler(addDate);
                    if(realTimeData['bendValue'] != null && realTimeData['bendValue'].length >0){
                        for(var a =0;a<realTimeData['bendValue'].length;a++){
                            if(a==0){
                                realTimeData['bendValue'][a][1]=2;
                            }
                        }
                    }
                    drawLineSsnd();
                }else{
                    closeLoading();
                }


                if(setInterval){
                    createSsndInterval();
                }
            }
        });

    }


    //打开遮罩
    function openLoading(){
        loading = layer.load(1, {
            shade: [0.1,'#fff'] //0.1透明度的白色背景
        });
    }
    //关闭遮罩
    function closeLoading(){
        layer.close(loading);
    }

    //修改实时数据的展现时间区间
    $(".time_period").on("change",function(e){
        var value = $(".time_period option:selected").val();
        periodTime = value;
        initEcharts();
    });

    function getTimeGranularitySql(startTime){

        var groupStr = "";
        var timePeriodValue = $(".time_period option:selected").val();
        if(timePeriodValue=="600000"){//10min
            groupStr = "time(50ms) fill(previous)";
        }else if(timePeriodValue=="1800000"){//30min
            groupStr = "time(50ms) fill(previous)";
        }else if(timePeriodValue=="3600000"){//1hour
            groupStr = "time(1s) fill(previous)";
        }else if(timePeriodValue=="7200000"){//2hour
            groupStr = "time(2s) fill(null)";
        }else if(timePeriodValue=="21600000"){//6hour
            groupStr = "time(3s) fill(null)";
        }else if(timePeriodValue=="43200000"){//12hour
            groupStr = "time(10s) fill(null)";
        }

        var sql = "select mean(temperature),mean(static_displayment),mean(bend_value),mean(v0) from" +
            " one_hour.original_data where beam_no = '"
            +currentBridge.beamNo+"' and time > "+startTime*1000000
            +" group by "+groupStr
            " order by time asc";
        return sql;
    }

});


